package com.ypan.mail.service.impl;

import com.ypan.mail.entity.MailEntity;
import com.ypan.mail.service.MailService;
import com.ypan.mail.utils.IpUtil;
import com.ypan.mail.utils.JsonResult;
import com.ypan.mail.utils.PinyinUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Set;

/**
 * @Author ypan
 * @Date on 2021/3/17  11:06
 * @Desc
 */
@Slf4j
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String senderMail;

    @Value("#{'${fiberhome.mails}'.split(',')}")
    private String[] mails;

    @Override
    public JsonResult send(MailEntity mailEntity) {
        if(!Arrays.asList(mails).contains(mailEntity.getMail())){
            log.info("邮箱未备份消息发送失败！请联系管理员！调用方:{} 接收方:{} 标题:{} 内容:{} ", mailEntity.getCaller(),mailEntity.getMail(),mailEntity.getTitle(),mailEntity.getContent());
            return JsonResult.error("邮箱未备份消息发送失败！请联系管理员!",mailEntity);
        }

        // new 一个简单邮件消息对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 和配置文件中的的username相同，相当于发送方
        message.setFrom(senderMail);
        // 收件人邮箱
        message.setTo(mailEntity.getMail());
        // 标题
        message.setSubject(PinyinUtil.toPinyin(mailEntity.getTitle()));
        // 正文
        message.setText(PinyinUtil.toPinyin(mailEntity.getContent()));
        // 发送
        mailSender.send(message);
        return JsonResult.ok(mailEntity);
    }
}
